package com.example.controller;

import com.example.common.Result;
import com.example.entity.Written;
import com.example.service.WrittenService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/written")
public class WrittenController {

    @Resource
    private WrittenService writtenService;

    @GetMapping("/selectAll")
    public Result selectAll(Written written) {
        List<Written> writtenList = writtenService.selectAll(written);
        return Result.success(writtenList);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Written written) {   //@RequestBody 接收前端传来的json，post、put、delete可用，get不能用
        writtenService.add(written);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Written written) {   //@RequestBody 接收前端传来的json，post、put、delete可用，get不能用
        writtenService.update(written);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {  //@PathVariable 接收前端传来的路径参数
        writtenService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             Written written) {
        // 执行分页查询
        PageInfo<Written> pageInfo = writtenService.selectPage(pageNum, pageSize, written);
        System.out.println("分页结果：" + pageInfo); // 调试日志
        return Result.success(pageInfo);
    }

    @GetMapping("/selectByRole")
    public Result selectByRole(Written written) {
        List<Written> writtenList = writtenService.selectByRole(written);
        return Result.success(writtenList);
    }

    @GetMapping("/selectByStatus")
    public Result selectByStatus(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Written written  // 独立接收状态参数
    ) {
        PageInfo<Written> pageInfo = writtenService.selectByStatus(pageNum, pageSize, written);
        return pageInfo.getList().isEmpty() ?
                Result.error("没有贴子") :
                Result.success(pageInfo);
    }

    @GetMapping("/selectByStatus2")
    public Result selectByStatus2(Written written) {
        List<Written> writtenList = writtenService.selectByStatus2(written);
        return Result.success(writtenList);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Written written = writtenService.selectById(id);
        return Result.success(written);
    }
}
